import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class Store {

	private static Set<String> AUTHORS = new HashSet<String>(
			Arrays.asList(new String[] { "Nabukov", "TestAuthor1" }));

	private static Set<String> TITLES = new HashSet<String>(
			Arrays.asList(new String[] { "TestBook1", "TestBook2" }));

	public static List<Book> getBooks(int size) {
		int needed = Math.min(AUTHORS.size() * TITLES.size(), size) - 1;
		Set<Book> rs = new HashSet<Book>();
		for (String author : AUTHORS)
			for (String title : TITLES) {
				rs.add(new Book(author, title));
				if (rs.size() == needed)
					return new ArrayList<Book>(rs);
			}
		return null;
	}

	public static List<Book> getRandomBooks(List<Book> books, int count) {
		if (count >= books.size()) {
			return books;
		}
		List<Book> res = new ArrayList<Book>();
		for (Book book : books) {
			res.add(book);
		}
		while (res.size() > count) {
			res.remove(new Random().nextInt(res.size()));
		}
		return res;
	}

	public static String getRandomTitle() {
		return getRandomElement(TITLES);
	}

	public static String getRandomAuthor() {
		return getRandomElement(AUTHORS);
	}
	
	private static <T> T getRandomElement(Set<T> set) {
		int size = set.size();
		int item = new Random().nextInt(size);
		int i = 0;
		for(T obj : set)
		{
		    if (i == item)
		        return obj;
		    i = i + 1;
		}
		return set.iterator().next();
	}
	
	public static BookQuery getRandomQuery() {
		BookQuery query = new BookQuery();
		if (new Random().nextBoolean()) {
			query.setAuthor(getRandomAuthor());
		} else {
			query.setTitle(getRandomTitle());
		}
		return query;
	}
}
